package com.lx.interceptor;

import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 性能监控
 *
 * @author 段誉
 * @create 2019-03-21 13:37
 */
public class PerformanceMonitorInterceptor extends HandlerInterceptorAdapter {
  private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<>("Performance-Monitor-Start-Time");
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler) throws Exception {
    //将接口请求时间绑定到当前线程
    startTimeThreadLocal.set(System.currentTimeMillis());
    return true;
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                              Object handler, Exception ex) throws Exception {
    //结束时间
    long endTime = System.currentTimeMillis();
    //得到线程的开始时间
    Long startTime = startTimeThreadLocal.get();
    //消耗的时间
    long consumeTime = endTime - startTime;
    System.out.println(String.format("[%s]消耗的时间为[%s]毫秒", request.getRequestURI(), consumeTime));
  }
}
